package com.freemalll.merchant.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.freemalll.common.core.exception.BusinessException;
import com.freemalll.common.core.http.HttpUtil;
import com.freemalll.merchant.constant.ConfigConstant;
import com.freemalll.merchant.constant.PuDaoConstant;
import com.freemalll.merchant.domain.dto.PuDaoDto;
import com.freemalll.merchant.domain.entity.MerLegalInfo;
import com.freemalll.merchant.service.PuDaoService;
import com.freemalll.merchant.utils.ConfigUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author songshixiong
 * @ClassName PuDaoServiceImpl
 * @description:
 * @date 2025年06月16日
 * @version: 1.0
 */
@Slf4j
@Service
public class PuDaoServiceImpl implements PuDaoService {


    private void initTempOrgTypeCount(Map<String, Integer> tempOrgTypeCount) {
        tempOrgTypeCount.put(PuDaoConstant.APPLY_EIGHTEEN_MONTH_NUM, 0);
        tempOrgTypeCount.put(PuDaoConstant.APPLY_ONE_MONTH_NUM, 0);
        tempOrgTypeCount.put(PuDaoConstant.APPLY_ONE_WEEK_NUM, 0);
        tempOrgTypeCount.put(PuDaoConstant.APPLY_ONE_YEAR_NUM, 0);
        tempOrgTypeCount.put(PuDaoConstant.APPLY_SIX_MONTH_NUM, 0);
        tempOrgTypeCount.put(PuDaoConstant.APPLY_SIXTY_MONTH_NUM, 0);
        tempOrgTypeCount.put(PuDaoConstant.APPLY_THREE_MONTH_NUM, 0);
        tempOrgTypeCount.put(PuDaoConstant.APPLY_TWO_YEAR_NUM, 0);
    }

    @Override
    public PuDaoDto parsingData(MerLegalInfo corporateInfoDto) {
        try {
            String checkPudaoData = ConfigUtil.getCoValue(ConfigConstant.CHECK_PUDAO_DATA);
            if (!StringUtils.hasText(checkPudaoData)) {
                throw BusinessException.businessValidateError("未配置同盾参数");
            }
            PuDaoDto dto = new PuDaoDto();
            JSONObject jsonObject = JSON.parseObject(checkPudaoData);
            String newUrl = jsonObject.getString("newUrl");
            log.info("-----------开始获取朴道报告-----------");
            Map<String, Object> params = new HashMap<>();
            params.put("certName", corporateInfoDto.getLegalMan());
            params.put("certNo", corporateInfoDto.getLegalManIdCard());
            params.put("mobile", corporateInfoDto.getLegalManPhone());
            //每次调用接口平台，都需要记录，那以身份证来查询便足够了
            newUrl += "?businessId=" + corporateInfoDto.getLegalManIdCard();
            String resJson = HttpUtil.sendPost(newUrl, params, 1);
            JSONObject pdJson = JSON.parseObject(resJson).getJSONObject("data");
            if (pdJson == null || !StringUtils.hasText(pdJson.getString("result_desc")) || !StringUtils.hasText(pdJson.getJSONObject("result_desc").getString("ANTIFRAUD"))) {
                throw BusinessException.businessValidateError("朴道报告获取失败");
            }

            Map<String, Map<String, Integer>> tdApplyMap = new HashMap<>();
            Map<String, Integer> tempOrgTypeCount;
            JSONArray riskItems = pdJson.getJSONObject("result_desc").getJSONObject("ANTIFRAUD").getJSONArray("risk_items");
            for (int riskItemsNum = 0; riskItemsNum < riskItems.size(); riskItemsNum++) {
                JSONObject pdRiskItem = riskItems.getJSONObject(riskItemsNum);
                JSONArray riskDetails = pdRiskItem.getJSONArray("risk_detail");
                if (riskDetails == null) {
                    continue;
                }
                for (int riskDetailsNum = 0; riskDetailsNum < riskDetails.size(); riskDetailsNum++) {
                    JSONObject pdRiskDetail = pdRiskItem.getJSONArray("risk_detail").getJSONObject(riskDetailsNum);
                    double rule_id = pdRiskItem.getDoubleValue("rule_id");
                    if (2224270 == rule_id) {
                        if (pdRiskDetail.containsKey("platform_detail")) {
                            JSONArray pdPlatformDetail = pdRiskDetail.getJSONArray("platform_detail");
                            for (int pdPlatformDetailNum = 0; pdPlatformDetailNum < pdPlatformDetail.size(); pdPlatformDetailNum++) {
                                double orgCount = pdPlatformDetail.getJSONObject(pdPlatformDetailNum).getDoubleValue("count");
                                String orgType = pdPlatformDetail.getJSONObject(pdPlatformDetailNum).getString("industry_display_name");
                                if (tdApplyMap.containsKey(orgType)) {
                                    tempOrgTypeCount = tdApplyMap.get(orgType);
                                } else {
                                    tempOrgTypeCount = new HashMap<>();
                                    initTempOrgTypeCount(tempOrgTypeCount);
                                }
                                tempOrgTypeCount.put("applyOneWeekNum", (int) orgCount);
                                tdApplyMap.put(orgType, tempOrgTypeCount);
                            }
                        }
                    }
                    if (2224272 == rule_id) {
                        if (pdRiskDetail.containsKey("platform_detail")) {
                            JSONArray pdPlatformDetail = pdRiskDetail.getJSONArray("platform_detail");
                            for (int pdPlatformDetailNum = 0; pdPlatformDetailNum < pdPlatformDetail.size(); pdPlatformDetailNum++) {
                                double orgCount = pdPlatformDetail.getJSONObject(pdPlatformDetailNum).getDoubleValue("count");
                                String orgType = pdPlatformDetail.getJSONObject(pdPlatformDetailNum).getString("industry_display_name");
                                if (tdApplyMap.containsKey(orgType)) {
                                    tempOrgTypeCount = tdApplyMap.get(orgType);
                                } else {
                                    tempOrgTypeCount = new HashMap<>();
                                    initTempOrgTypeCount(tempOrgTypeCount);
                                }
                                tempOrgTypeCount.put("applyOneMonthNum", (int) orgCount);
                                tdApplyMap.put(orgType, tempOrgTypeCount);
                            }
                        }
                    }
                    if (2224274 == rule_id) {
                        if (pdRiskDetail.containsKey("platform_detail")) {
                            JSONArray pdPlatformDetail = pdRiskDetail.getJSONArray("platform_detail");
                            for (int pdPlatformDetailNum = 0; pdPlatformDetailNum < pdPlatformDetail.size(); pdPlatformDetailNum++) {
                                double orgCount = pdPlatformDetail.getJSONObject(pdPlatformDetailNum).getDoubleValue("count");
                                String orgType = pdPlatformDetail.getJSONObject(pdPlatformDetailNum).getString("industry_display_name");
                                if (tdApplyMap.containsKey(orgType)) {
                                    tempOrgTypeCount = tdApplyMap.get(orgType);
                                } else {
                                    tempOrgTypeCount = new HashMap<>();
                                    initTempOrgTypeCount(tempOrgTypeCount);
                                }
                                tempOrgTypeCount.put("applyThreeMonthNum", (int) orgCount);
                                tdApplyMap.put(orgType, tempOrgTypeCount);
                            }
                        }
                    }
                    if (2224276 == rule_id) {
                        if (pdRiskDetail.containsKey("platform_detail")) {
                            JSONArray pdPlatformDetail = pdRiskDetail.getJSONArray("platform_detail");
                            for (int pdPlatformDetailNum = 0; pdPlatformDetailNum < pdPlatformDetail.size(); pdPlatformDetailNum++) {
                                double orgCount = pdPlatformDetail.getJSONObject(pdPlatformDetailNum).getDoubleValue("count");
                                String orgType = pdPlatformDetail.getJSONObject(pdPlatformDetailNum).getString("industry_display_name");
                                if (tdApplyMap.containsKey(orgType)) {
                                    tempOrgTypeCount = tdApplyMap.get(orgType);
                                } else {
                                    tempOrgTypeCount = new HashMap<>();
                                    initTempOrgTypeCount(tempOrgTypeCount);
                                }
                                tempOrgTypeCount.put("applySixMonthNum", (int) orgCount);
                                tdApplyMap.put(orgType, tempOrgTypeCount);
                            }
                        }
                    }
                    if (2224278 == rule_id) {
                        if (pdRiskDetail.containsKey("platform_detail")) {
                            JSONArray pdPlatformDetail = pdRiskDetail.getJSONArray("platform_detail");
                            for (int pdPlatformDetailNum = 0; pdPlatformDetailNum < pdPlatformDetail.size(); pdPlatformDetailNum++) {
                                double orgCount = pdPlatformDetail.getJSONObject(pdPlatformDetailNum).getDoubleValue("count");
                                String orgType = pdPlatformDetail.getJSONObject(pdPlatformDetailNum).getString("industry_display_name");
                                if (tdApplyMap.containsKey(orgType)) {
                                    tempOrgTypeCount = tdApplyMap.get(orgType);
                                } else {
                                    tempOrgTypeCount = new HashMap<>();
                                    initTempOrgTypeCount(tempOrgTypeCount);
                                }
                                tempOrgTypeCount.put("applyOneYearNum", (int) orgCount);
                                tdApplyMap.put(orgType, tempOrgTypeCount);
                            }
                        }
                    }
                    if (2224280 == rule_id) {
                        if (pdRiskDetail.containsKey("platform_detail")) {
                            JSONArray pdPlatformDetail = pdRiskDetail.getJSONArray("platform_detail");
                            for (int pdPlatformDetailNum = 0; pdPlatformDetailNum < pdPlatformDetail.size(); pdPlatformDetailNum++) {
                                double orgCount = pdPlatformDetail.getJSONObject(pdPlatformDetailNum).getDoubleValue("count");
                                String orgType = pdPlatformDetail.getJSONObject(pdPlatformDetailNum).getString("industry_display_name");
                                if (tdApplyMap.containsKey(orgType)) {
                                    tempOrgTypeCount = tdApplyMap.get(orgType);
                                } else {
                                    tempOrgTypeCount = new HashMap<>();
                                    initTempOrgTypeCount(tempOrgTypeCount);
                                }
                                tempOrgTypeCount.put("applyEighteenMonthNum", (int) orgCount);
                                tdApplyMap.put(orgType, tempOrgTypeCount);
                            }
                        }
                    }
                    if (2224282 == rule_id) {
                        if (pdRiskDetail.containsKey("platform_detail")) {
                            JSONArray pdPlatformDetail = pdRiskDetail.getJSONArray("platform_detail");
                            for (int pdPlatformDetailNum = 0; pdPlatformDetailNum < pdPlatformDetail.size(); pdPlatformDetailNum++) {
                                double orgCount = pdPlatformDetail.getJSONObject(pdPlatformDetailNum).getDoubleValue("count");
                                String orgType = pdPlatformDetail.getJSONObject(pdPlatformDetailNum).getString("industry_display_name");
                                if (tdApplyMap.containsKey(orgType)) {
                                    tempOrgTypeCount = tdApplyMap.get(orgType);
                                } else {
                                    tempOrgTypeCount = new HashMap<>();
                                    initTempOrgTypeCount(tempOrgTypeCount);
                                }
                                tempOrgTypeCount.put("applyTwoYearNum", (int) orgCount);
                                tdApplyMap.put(orgType, tempOrgTypeCount);
                            }
                        }
                    }
                    if (2224284 == rule_id) {
                        if (pdRiskDetail.containsKey("platform_detail")) {
                            JSONArray pdPlatformDetail = pdRiskDetail.getJSONArray("platform_detail");
                            for (int pdPlatformDetailNum = 0; pdPlatformDetailNum < pdPlatformDetail.size(); pdPlatformDetailNum++) {
                                double orgCount = pdPlatformDetail.getJSONObject(pdPlatformDetailNum).getDoubleValue("count");
                                String orgType = pdPlatformDetail.getJSONObject(pdPlatformDetailNum).getString("industry_display_name");
                                if (tdApplyMap.containsKey(orgType)) {
                                    tempOrgTypeCount = tdApplyMap.get(orgType);
                                } else {
                                    tempOrgTypeCount = new HashMap<>();
                                    initTempOrgTypeCount(tempOrgTypeCount);
                                }
                                tempOrgTypeCount.put("applySixtyMonthNum", (int) orgCount);
                                tdApplyMap.put(orgType, tempOrgTypeCount);
                            }
                        }
                    }
                }
            }

            Set<Map.Entry<String, Map<String, Integer>>> entries = tdApplyMap.entrySet();
            for (Map.Entry<String, Map<String, Integer>> entry : entries) {
                dto.setApplyOneWeekNum(dto.getApplyOneWeekNum() + (entry.getValue().get(PuDaoConstant.APPLY_ONE_WEEK_NUM) == null ? 0 : entry.getValue().get(PuDaoConstant.APPLY_ONE_WEEK_NUM)));
                dto.setApplyOneMonthNum(dto.getApplyOneMonthNum() + (entry.getValue().get(PuDaoConstant.APPLY_ONE_MONTH_NUM) == null ? 0 : entry.getValue().get(PuDaoConstant.APPLY_ONE_MONTH_NUM)));
                dto.setApplyThreeMonthNum(dto.getApplyThreeMonthNum() + (entry.getValue().get(PuDaoConstant.APPLY_THREE_MONTH_NUM) == null ? 0 : entry.getValue().get(PuDaoConstant.APPLY_THREE_MONTH_NUM)));
                dto.setApplySixMonthNum(dto.getApplySixMonthNum() + (entry.getValue().get(PuDaoConstant.APPLY_SIX_MONTH_NUM) == null ? 0 : entry.getValue().get(PuDaoConstant.APPLY_SIX_MONTH_NUM)));
                dto.setApplyOneYearNum(dto.getApplyOneYearNum() + (entry.getValue().get(PuDaoConstant.APPLY_ONE_YEAR_NUM) == null ? 0 : entry.getValue().get(PuDaoConstant.APPLY_ONE_YEAR_NUM)));
                dto.setApplyEighteenMonthNum(dto.getApplyEighteenMonthNum() + (entry.getValue().get(PuDaoConstant.APPLY_EIGHTEEN_MONTH_NUM) == null ? 0 : entry.getValue().get(PuDaoConstant.APPLY_EIGHTEEN_MONTH_NUM)));
                dto.setApplyTwoYearNum(dto.getApplyTwoYearNum() + (entry.getValue().get(PuDaoConstant.APPLY_TWO_YEAR_NUM) == null ? 0 : entry.getValue().get(PuDaoConstant.APPLY_TWO_YEAR_NUM)));
                dto.setApplySixtyMonthNum(dto.getApplySixtyMonthNum() + (entry.getValue().get(PuDaoConstant.APPLY_SIXTY_MONTH_NUM) == null ? 0 : entry.getValue().get(PuDaoConstant.APPLY_SIXTY_MONTH_NUM)));
            }
            //同盾综合评分
            dto.setFinalScore(pdJson.getJSONObject("result_desc").getJSONObject("ANTIFRAUD").getInteger("final_score"));
            //同盾最终决策结果
            dto.setFinalDecision(pdJson.getJSONObject("result_desc").getJSONObject("ANTIFRAUD").getString("final_decision"));
            return dto;
        } catch (IOException e) {
            log.error("同盾查询异常：{}", e.getMessage());
        }
        return null;
    }
}
